package com.bailiban.controller;

import com.bailiban.entity.Permission;
import com.bailiban.entity.Role;
import com.bailiban.service.PermissionService;
import com.bailiban.service.RoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author zhulang
 * @Classname RoleController
 * @Description RoleController
 */
@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @GetMapping("findAll")
    @Secured({"ROLE_SELLER", "ROLE_VIP"})
    public ModelAndView findAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "3") Integer size) {
        PageInfo<Role> pageInfo = roleService.findAll(page, size);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("role-list");
        modelAndView.addObject("roleList", pageInfo);
        return modelAndView;
    }

    @PostMapping("save")
    @Secured("ROLE_BOSS")
    public String save(Role role) {
        Role insert = roleService.insert(role);
        return "redirect:/role/findAll.do";
    }

    @GetMapping("findRoleByIdAndAllPermission")
    public ModelAndView findRoleByIdAndAllPermission(Integer roleId) {
        List<Permission> permissionList = permissionService.findOtherPermissionByRoleId(roleId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("role-permission-add");
        modelAndView.addObject("permissionList", permissionList);
        modelAndView.addObject("roleId", roleId);
        return modelAndView;
    }

    @PostMapping("addPermissionToRole")
    public String addPermissionToRole(Integer roleId, Integer[] ids) {
        Integer integer = roleService.addPermissionToRole(roleId, ids);
        return "redirect:/role/findAll.do";
    }
}
